const authentication = () => {
    if ("clipboard" in navigator) {
        return new Promise((resolve, reject) => {
            navigator.permissions.query({ name: "clipboard-read" }).then(
                (result) => {
                    if (result.state == "granted" || result.state == "prompt") {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                },
                (error) => {
                    reject(error);
                }
            );
        });
    } else {
        alert("该浏览器暂不支持，请使用最新版本的GoogleChrome浏览");
        return Promise.resolve(false);
    }
};

let locations = []

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        locations = request.filter(item => item.checked == true).map(item => item.location)
        doWork()
        // console.log(locations)
    });

function doWork() {
    chrome.storage.local.get('locations', ({ locations }) => {
        locations = locations.filter(item => item.checked == true).map(item => item.location)
        // console.log('激活locations:',locations)
        $('.copy-btn-id').remove()
        $("a:contains('馆藏')").each(function (i) {
            let reg = /馆藏\([0-9]\d*\)/
            let text = $(this).text()
            const a_this = this//a标签
            if (reg.test(text)) {
                let num = text.match(/[0-9]\d*/g)[0]
                if (num > 0) {
                    let trs = $(this).parent().parent().next().children().first().children().first().children()
                    let flag = false
                    $.each(trs, function (i, tr) {//i第几行
                        if (i > 0) {//第0行是标题
                            let n = $(this).children().eq(3).text().match(/[0-9]\d*/)[0]//课件数量
                            let loc = $(this).children().eq(2).text().trim()//所在馆
                            // console.log(`n:${n}, loc:${loc}`)
                            // console.log($(this).children().eq(3).text().match(/[0-9]\d*/)[0])
                            // console.log(`是否在列表:${locations.indexOf(loc) != -1}`)
                            if (n > 0 && locations.indexOf(loc) != -1) {
                                // console.log(`列表：${locations}`) 
                                flag = true
                                $(this).css("color", "green")
                                var btn = document.createElement("button")
                                btn.textContent = "复制"
                                btn.className = "copy-btn-id"
                                this.appendChild(btn)
                                const row_this = this
                                btn.addEventListener('click', function () {
                                    authentication().then(() => {
                                        let title = $(a_this).parent().parent().parent().prev().children().first().children().first().text().trim()
                                        let num = $(row_this).children().eq(0).text().trim()
                                        let item = `${title}--${num}`
                                        navigator.clipboard.writeText(item).then(
                                            () => {
                                                console.log("粘贴文本成功");
                                                chrome.storage.local.get('items', ({ items }) => {
                                                    items.push(item)
                                                    chrome.storage.local.set({ items: items });
                                                })

                                            },
                                            () => {
                                                console.log("clipboard write failed");
                                            }
                                        );
                                    })
                                })


                            } else {
                                $(this).css("color", "")
                            }
                        }
                    })
                    
                    $(a_this).css("color", flag?"green":"")

                }

            }
        })


    })

}

window.onload = function () {
    setTimeout(() => {
        doWork()
    }, 1000)


}